<template>
  <nw-PageTitle :title="$t('system.versionInfo')" isBack />
  <nw-PageContainer>
    <view class="content">
      <view class="title" style="margin-top: 100px">协议调试</view>
      <!--            <view style="margin-top: 40rpx;">网络服务测试</view>
            <button class="btn" @click="startNetworkServer">启动UDP、TCP服务</button>
            <button class="btn" @click="sendDeviceMsg">发送消息</button>
            <button class="btn" @click="stopNetworkServer">停止UDP、TCP服务</button> -->

      <!--            <view style="margin-top: 40rpx;">UDP测试</view>
            <button class="btn" @click="startUdp">启动UDP</button>
            <button class="btn" @click="sendUdpMsg">发送UDP消息</button>
            <button class="btn" @click="stopUdp">停止UDP</button>
            <view style="margin-top: 40rpx;">TCPServer测试</view>
            <button class="btn" @click="startTcpServer">启动TCPServer</button>
            <button class="btn" @click="sendTcpServerMsg">发送TCP消息</button>
            <button class="btn" @click="closeTcpClient">断开TCP客户端</button>
            <button class="btn" @click="stopTcpServer">停止TCPServer</button> -->

      <!--            <button class="btn" @click="stopProtocolServer">停止协议服务</button>
            <button class="btn" @click="cleanBindDeviceList">清空绑定的设备列表</button>
            <button class="btn" @click="cleanCookItemList">清空烹饪记录</button>
            <button class="btn" @click="sendRecipeToDevice">发送菜谱</button>
            <button class="btn" @click="getCookItemList">查看当前烹饪记录</button>
            <button class="btn" @click="doTest">测试</button>
            <button class="btn" @click="electronicScaleTest">电子秤</button>
            <button class="btn" @click="rangeHoodControlTest">油烟机</button>
            <button class="btn" @click="closeDeviceTcp">断开设备</button> -->

      <button class="btn" @click="deviceCountLimit">设置-限制使用</button>
      <button class="btn" @click="resetFactory">设置-恢复出厂</button>
      <button class="btn" @click="emergencyOperation">紧急处理</button>
      <button class="btn" @click="pauseRecipe">暂停炒菜</button>
      <button class="btn" @click="resumeRecipe">继续炒菜</button>
      <button class="btn" @click="lingxinText2Voice">灵芯文本转语音</button>
      <button class="btn" @click="lingxinVoice2Text">灵芯语音转文本指令</button>
      <button class="btn" @click="testFile">测试文件</button>
      <button class="btn" @click="startRecorder">开始录音</button>
      <button class="btn" @click="stopRecorder">停止录音</button>
    </view>
    <view>
      <view>UDP客户端</view>
      <view v-for="(item, index) in deviceOfBroadcast" :key="item.sn">
        {{ item.sn }} - {{ item.ip }} - {{ item.port }}
      </view>

      <view>TCP客户端</view>
      <view v-for="(item, index) in dviceOfOnline" :key="item.sn">
        设备标识：{{ item.sn }} 设备会话ID：{{ item.sessionId }} 设备IP：{{
          item.ip
        }}
        设备端口：{{ item.port }}
      </view>
    </view>
  </nw-PageContainer>
</template>

<script setup>
import { getCurrentInstance, onMounted, onBeforeUnmount } from 'vue'
const props = defineProps({
  title: {
    type: String,
    default: ''
  }
})

const loading = ref(true)
const tableList = ref([])

// 获取当前组件实例
const instance = getCurrentInstance()

import emitter from '@/utils/emitter'
onMounted(() => {
  // 监听事件
  emitter.on('device-manual-add-seasoning-result', data => {
    // {"deviceSn":"N21250523152535","driverId":"2201","result":1}
    console.log('收到调料投放结果事件:', data)
  })
})
onBeforeUnmount(() => {
  // 组件销毁时移除监听
  emitter.off('device-manual-add-seasoning-result')
})

///////////////////// 调试功能 ///////////////
import { deviceProtocolService } from '@/service/deviceProtocolService.js'
function stopProtocolServer() {
  deviceProtocolService.destroyNetworkServer()
}
const { allDeviceList, bindDeviceList } = storeToRefs(useDeviceStore())
function cleanBindDeviceList() {
  bindDeviceList.value.splice(0, bindDeviceList.value.length) // 清空数组
}
const { cookingItemList } = storeToRefs(useCookingStore())
function cleanCookItemList() {
  cookingItemList.value.splice(0, cookingItemList.value.length) // 清空数组
}

import { v4 as uuidv4 } from 'uuid'
import { RecipeTasteStyle } from '@/interface/recipe'
import { CookItemStatus } from '@/interface/cooking.js'
import { getUuid } from '@/utils/index.js'
import { deviceProtocolRecipeService } from '@/service/deviceProtocolRecipeService.js'
import { deviceProtocolManualService } from '@/service/deviceProtocolManualService'
import { deviceProtocolListenerService } from '@/service/deviceProtocolListenerService'
const { recipeLibraryList, recipeFormulatingList, recipeCollectionList } =
  storeToRefs(useRecipeStore())
function sendRecipeToDevice() {
  console.log('烹饪记录：', cookingItemList.value)
  console.log('菜谱库：', recipeLibraryList.value)
  console.log('绑定设备：', bindDeviceList.value)
  let recipe = recipeLibraryList.value[0]
  let device = bindDeviceList.value[0]

  deviceProtocolRecipeService
    .sendRecipe(device, recipe)
    .then(r => {
      console.log('发送消息成功：', r)

      // 记录烹饪记录
      const uuid = uuidv4()
      console.log(uuid.replace(/-/g, ''))
      cookingItemList.value.push({
        cookingId: getUuid(), // 烹饪记录ID，全局唯一ID，UUID
        deviceSn: device.sn, // 设备序列号
        deviceName: device.name, // 设备名称
        recipeId: recipe.id, // 菜谱ID
        recipeName: recipe.name, // 菜谱名称
        cookCount: 1, // 烹饪份数，默认为1
        tasteStyle: RecipeTasteStyle.Other, // 口味风格：0-其他、1-不辣、2-微辣、3-中辣、4-超辣、5-麻辣
        status: CookItemStatus.NotStart, // 烹饪状态，1-未开始（准备中），2-烹饪中，3-已取消，4-已暂停，5-已完成
        step: 0, // 烹饪到第几步，0-代表未开始
        stepStartTime: 0, // 步骤的开始时间(毫秒)
        cookStartTime: 0, // 烹饪开始时间(毫秒)，第1步骤开始的时间作为烹饪开始时间
        cookEndTime: 0, // 烹饪结束时间(毫秒)
        operatorUserId: '1', // 操作员用户ID
        createTime: Date.now() // 烹饪任务创建时间(毫秒)
      })
    })
    .catch(e => {
      console.log('发送消息失败：', e)
    })
}

function doTest() {
  let deviceSn = 'N21250523152535'
  // let recipeId = 'R20250705113547'
  // let cookingStore = useCookingStore()
  // console.log("烹饪记录：", cookingStore.cookingItemList)
  // let targetCookItem = cookingStore.getLatestCookInfoForDevice(deviceSn, recipeId)
  // if (!targetCookItem) {
  //     console.log("没有找到设备当前烹饪信息：", deviceSn)
  //     return
  // }
  // console.log("设备当前烹饪信息：", targetCookItem)

  // deviceProtocolListenerService.unregisterDeviceMessageCallback(keyStr)
  deviceProtocolManualService
    .manualAddSeasoning(deviceSn, [{ driverId: '2201', goal: 10 }])
    .then(r => {
      console.log('发送消息成功：', r)
    })
    .catch(e => {
      console.log('发送消息失败：', e)
    })
}

function getCookItemList() {
  let deviceSn = 'N21250523152535'
  let recipeId = 'R20250705113547'
  let cookingStore = useCookingStore()
  console.log('所有烹饪记录：', cookingStore.cookingItemList)
  let targetCookItem = cookingStore.getLatestCookInfoForDevice(deviceSn)
  if (!targetCookItem) {
    console.log('没有找到设备当前烹饪信息：', deviceSn)
    return
  }
  console.log('设备当前烹饪信息：', targetCookItem)
}

import { deviceProtocolEquipmentService } from '@/service/deviceProtocolEquipmentService.js'
function electronicScaleTest() {
  // 食材盒重量
  // deviceProtocolEquipmentService.electronicScaleFoodPreparation("N21250523152535",
  // {
  //     weight1: 100,
  //     weight2: 35,
  //     weight3: 375,
  //     weight4: 3257,
  //     },
  // )
  // .then(r => {
  //     console.log("发送消息成功：", r)
  // })
  // .catch(e => {
  //     console.log("发送消息失败：", e)
  // })

  // 设置食材盒空重
  // deviceProtocolEquipmentService.electronicScaleSetEmptyBoxWeight("N21250523152535", 100)
  // .then(r => {
  //     console.log("发送消息成功：", r)
  // })
  // .catch(e => {
  //     console.log("发送消息失败：", e)
  // })

  // 7.6 设置默认重量显示（电子秤）
  deviceProtocolEquipmentService
    .electronicScaleSetWeightUnit('N21250523152535', 1)
    .then(r => {
      console.log('发送消息成功：', r)
    })
    .catch(e => {
      console.log('发送消息失败：', e)
    })
}
function rangeHoodControlTest() {
  // 7.7 设置风扇灯光（油烟机）
  // deviceProtocolEquipmentService.rangeHoodFanControl("N21250523152535", 2, 2)
  // .then(r => {
  //     console.log("发送消息成功：", r)
  // })
  // .catch(e => {
  //     console.log("发送消息失败：", e)
  // })

  // 7.8 关闭油烟机（油烟机）
  deviceProtocolEquipmentService
    .rangeHoodPoweroffControl('N21250523152535')
    .then(r => {
      console.log('发送消息成功：', r)
    })
    .catch(e => {
      console.log('发送消息失败：', e)
    })
}

function closeDeviceTcp() {
  deviceProtocolEquipmentService
    .closeDeviceConnection('N21250523152535')
    .then(r => {
      console.log('断开TCP成功：', r)
    })
    .catch(e => {
      console.log('断开TCP失败：', e)
    })
}

import {
  MsgType,
  DeviceMessageSend,
  DeviceMessageReceive
} from '@/utils/deviceProtocolUtil.js'
import { useCookingStore } from '../../../store/modules/cooking'
import { func } from '@climblee/uv-ui/libs/function/test'

let deviceOfBroadcast = deviceProtocolService.getBroadcastDeviceList()
let dviceOfOnline = deviceProtocolService.getOnlineDeviceList()

let startNetworkServer = function () {
  deviceProtocolService.setupNetworkServer()
}
let sendDeviceMsg = function () {
  // deviceProtocolService.sendRecipe("N21250523152535", {})
  // deviceProtocolService.startCooking("N21250523152535", "R20250620140708")
  // deviceProtocolService.pauseCooking("N21250523152535")
  // deviceProtocolService.resumeCooking("N21250523152535")
}
let stopNetworkServer = function () {
  deviceProtocolService.destroyNetworkServer()
}

import { deviceProtocolSettingService } from '@/service/deviceProtocolSettingService'
function deviceCountLimit() {
  deviceProtocolSettingService
    .modifyDeviceCountLimit('861250523152511', 20)
    .then(data => {
      console.log('--------------发送限制次数命令成功')
    })
    .catch(() => {
      console.log('--------------发送限制次数命令失败')
    })
}
function resetFactory() {
  deviceProtocolSettingService
    .deviceFactoryReset('861250523152511')
    .then(data => {
      console.log('--------------发送恢复出厂命令成功')
    })
    .catch(() => {
      console.log('--------------发送恢复出厂命令失败')
    })
}

function emergencyOperation() {
  deviceProtocolManualService
    .deviceEmergencyOperation('861250523152511', '0102', 20)
    .then(data => {
      console.log('--------------发送恢复出厂命令成功')
    })
    .catch(() => {
      console.log('--------------发送恢复出厂命令失败')
    })
}

function pauseRecipe() {
  deviceProtocolRecipeService
    .pauseCooking('861250523152511')
    .then(r => {
      console.log('暂停消息成功：', r)
    })
    .catch(e => {
      console.log('暂停消息失败：', e)
    })
}
function resumeRecipe() {
  deviceProtocolRecipeService
    .pauseCooking('861250523152511')
    .then(r => {
      console.log('恢复消息成功：', r)
    })
    .catch(e => {
      console.log('恢复消息失败：', e)
    })
}

import { lingxinApiService } from '@/service/lingxinApiService'
function lingxinText2Voice() {
  // const { appId, asrLicense } = storeToRefs(useAppAsrLicenseStore())
  // appId.value = "BD08514BB4B6C6DE14DF0D9F4E061F41"
  // asrLicense.value = "0015ca37-8ec8-4162-9f0d-3e85748a8cfc"
  lingxinApiService
    .textToVoice('番茄炒蛋烹饪已完成')
    .then(audioFilePath => {
      console.log('文本转语音成功：', audioFilePath)
      // let hx = arrayBufferToHex(r)
      // console.log(hx)
      // saveFile(hx)
    })
    .catch(e => {
      console.log('文本转语音失败：', e)
    })
}
// let audioData = hexToArrayBuffer(audioHexData)
function lingxinVoice2Text() {
  let audioFilePath = '/storage/emulated/0/Android/data/uni.app.UNI5930F2F/files/audios/audio_recorder_111.aac'
  // let audioFilePath = "/storage/emulated/0/Android/data/uni.app.UNI5930F2F/apps/__UNI__5930F2F/doc/uniapp_temp_1762510676361/recorder/1762510725100.aac"
  lingxinApiService
    .voiceToText(audioFilePath)
    .then(jsonData => {
      console.log('语音转文本成功：', jsonData)
    })
    .catch(e => {
      console.log('语音转文本失败：', e)
    })
}
let audioHexData =''
function hexToArrayBuffer(hexString) {
  // 清理 HEX 字符串（移除空格等）
  const cleanHex = hexString.replace(/[^0-9a-f]/gi, '').toLowerCase()

  // 检查长度是否为偶数
  if (cleanHex.length % 2 !== 0) {
    throw new Error('HEX字符串长度必须为偶数')
  }

  // 创建 ArrayBuffer
  const buffer = new ArrayBuffer(cleanHex.length / 2)
  const view = new Uint8Array(buffer)

  // 逐个字节转换
  for (let i = 0; i < cleanHex.length; i += 2) {
    const byteHex = cleanHex.substr(i, 2)
    const byteValue = parseInt(byteHex, 16)

    if (isNaN(byteValue)) {
      throw new Error(`无效的HEX字符: ${byteHex}`)
    }

    view[i / 2] = byteValue
  }

  return buffer
}

import AudioFileManager from '@/js_sdk/AudioFileManager/index.js'
function testFile() {
  // console.log("准备保存文件")
  // let audioData = hexToArrayBuffer(audioHexData)
  // // console.log("文件保存路径：", AudioFileManager.writeData(audioData))
  // AudioFileManager.writeDataAsync(audioData)
  // .then(saveFilePath => {
  //     console.log("存储完成：", saveFilePath)
  // })
  // .catch(error => {
  //     console.log('存储语音数据到文件错误：', error)
  // })

  console.log('准备读取文件')
  let readFilePath = '/storage/emulated/0/Android/data/uni.app.UNI5930F2F/files/audios/audio_20251107153745.mp3'
  // let audioData = AudioFileManager.readData(readFilePath)
  // let hx = arrayBufferToHex(audioData)
  // console.log(hx)
  
  AudioFileManager.readDataAsync(readFilePath)
  .then(audioData => {
      let hx = arrayBufferToHex(audioData)
      console.log(hx)
  })
  .catch(e => {
      console.log("错误：", e)
  })
}

const recorderManager = uni.requireNativePlugin?.('audio-recorder')
function startRecorder() {
    console.log("开始录音")
    let readFilePath = '/storage/emulated/0/Android/data/uni.app.UNI5930F2F/files/audios/audio_123456.aac'

    recorderManager.setIsDebug(true)
    recorderManager.start(
        readFilePath,
        startResult => {
            console.log(startResult)
        },
        stopResult => {
            console.log(stopResult)
        },
        error => {
            console.log(error)
        }
    )
}

function stopRecorder() {
    console.log("停止录音")
    recorderManager.stop()
}
</script>

<style lang="scss" scoped>
.content {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  width: 100%;

  .title {
    font-size: 20 * 2rpx;
    font-weight: bold;
    color: var(--color-333);
  }

  .btn {
    margin-top: 10px;
    width: 90%;
  }
}
</style>
